package com.truyentranh.modules.local;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseDialogListener;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.LoginButton;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionStore;
import com.facebook.android.Utility;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.truyentranh.R;
import com.truyentranh.data.MenuMoreItem;
import com.truyentranh.main.ComicBussiness;
import com.truyentranh.main.ComicSessionStore;
import com.truyentranh.main.DisplayUtils;
import com.truyentranh.modules.epicvn.EpicVnActivity;
import com.truyentranh.modules.haivl.HaiVLActivity;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.GlobalData;
import com.truyentranh.utils.IImageCached;
import com.truyentranh.utils.Logger;
import com.truyentranh.utils.sqllite.datasource.TopicHaiBlData;

public class MoreActivity extends Activity implements OnItemClickListener {

	ListView mainContentList;
	ArrayList<MenuMoreItem> modules;

	private LoginButton mLoginButton;
	private Handler mHandler;
	final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
	final static int PICK_EXISTING_PHOTO_RESULT_CODE = 1;
	ProgressDialog dialog;
	String[] permissions = { "offline_access",
			"publish_stream", 
			"user_photos", 
			"publish_actions",
			"publish_checkins",
			"photo_upload" };
	private ImageView userAvatar;
	private TextView userDisplayName;
	private FrameLayout userInfoLayout;
	private Button logoutButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.more_activity_main);
		mainContentList = (ListView) findViewById(R.id.mainContentList);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText("Nhi�?u hơn nữa...");
		getMenuMore();

		Button button = (Button) findViewById(R.id.btnMoreFunctions);
		button.setVisibility(View.GONE);

		MoreMenuRenderAdapter haiBLModulesRenderAdapter = new MoreMenuRenderAdapter(getApplicationContext(), 1, 1, modules);
		mainContentList.setAdapter(haiBLModulesRenderAdapter);

		mainContentList.setOnItemClickListener(this);
		int[] colors = { 0, 0xFF000000, 0 };
		mainContentList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
		mainContentList.setDividerHeight(1);

		AppSettingParams.SCREEN_WIDTH = getWindowManager().getDefaultDisplay().getWidth();
		AppSettingParams.SCREEN_HEIGHT = getWindowManager().getDefaultDisplay().getHeight();

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					finish();
				}
			});
		}

		mHandler = new Handler();

		mLoginButton = (LoginButton) findViewById(R.id.btnConnectFacebook);
		userAvatar = (ImageView) findViewById(R.id.userAvatar);
		userDisplayName = (TextView) findViewById(R.id.userDisplayName);
		userInfoLayout = (FrameLayout) findViewById(R.id.userInfo);
		logoutButton = (Button) findViewById(R.id.btnLogout);

		logoutButton.setOnClickListener(doLogout);
		// restore session if one exists

		SessionEvents.addAuthListener(new FbAPIsAuthListener());
		SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
		/*
		 * Source Tag: login_tag
		 */
		mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

		if (Utility.mFacebook.isSessionValid()) {
			requestUserData();
		}
	}

	OnClickListener doLogout = new OnClickListener() {

		public void onClick(View v) {

			DisplayUtils.openConfirmDialog("�?ăng xuất", "Bạn muốn đăng xuất tài khoản Facebook?", MoreActivity.this, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {

					if (Utility.mFacebook != null) {
						try {
							mLoginButton.doLogout();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}, null);

		}
	};
	
	public void setInfoAndVisibleLayout(String avatar, String userName) {
		if (avatar != null && userName != null) {
			userInfoLayout.setVisibility(View.VISIBLE);
			userDisplayName.setText(userName);
			Logger.logMe("avatar = " + avatar);
			
			GlobalData.mAQ.id(userAvatar).image(avatar, true, true, 50, 0,
	                new BitmapAjaxCallback() {
	            @Override
	            public void callback(String url,
	                    ImageView imageview, Bitmap bm,
	                    AjaxStatus status) 
	            {            	
	                if (bm != null) 
	                {
	                	if (userAvatar != null) {
							userAvatar.setImageBitmap(bm);
							userAvatar.setVisibility(View.VISIBLE);
						}
	                } 
	            }
	        });
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	public void onResume() {
		super.onResume();
		if (Utility.mFacebook != null) {
			SessionStore.restore(Utility.mFacebook, this);
			if (!Utility.mFacebook.isSessionValid()) {
				System.out.println("You are logged out!");
			} else {
				Utility.mFacebook.extendAccessTokenIfNeeded(this, null);
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println("onActivityResultonActivityResultonActivityResult");
		switch (requestCode) {
		/*
		 * if this is the activity result from authorization flow, do a call
		 * back to authorizeCallback Source Tag: login_tag
		 */
		case AUTHORIZE_ACTIVITY_RESULT_CODE: {
			Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
			break;
		}
		/*
		 * if this is the result for a photo picker from the gallery, upload the
		 * image after scaling it. You can use the Utility.scaleImage() function
		 * for scaling
		 */
		case PICK_EXISTING_PHOTO_RESULT_CODE: {
			if (resultCode == Activity.RESULT_OK) {
				Uri photoUri = data.getData();
				if (photoUri != null) {
					Bundle params = new Bundle();
					try {
						params.putByteArray("photo", Utility.scaleImage(getApplicationContext(), photoUri));
					} catch (IOException e) {
						e.printStackTrace();
					}
					params.putString("caption", "FbAPIs Sample App photo upload");
					Utility.mAsyncRunner.request("me/photos", params, "POST", new PhotoUploadListener(), null);
				} else {
					Toast.makeText(getApplicationContext(), "Error selecting image from the gallery.", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getApplicationContext(), "No image selected for upload.", Toast.LENGTH_SHORT).show();
			}
			break;
		}
		}
	}

	/*
	 * callback for the apprequests dialog which sends an app request to user's
	 * friends.
	 */
	public class AppRequestsListener extends BaseDialogListener {

		public void onComplete(Bundle values) {
			Toast toast = Toast.makeText(getApplicationContext(), "App request sent", Toast.LENGTH_SHORT);
			toast.show();
		}

		public void onFacebookError(FacebookError error) {
			Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
		}

		public void onCancel() {
			Toast toast = Toast.makeText(getApplicationContext(), "App request cancelled", Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	/*
	 * callback after friends are fetched via me/friends or fql query.
	 */
	public class FriendsRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			dialog.dismiss();
			System.out.println("FriendsRequestListener onComplete");
			// Intent myIntent = new Intent(getApplicationContext(),
			// FriendsList.class);
			// myIntent.putExtra("API_RESPONSE", response);
			// myIntent.putExtra("METHOD", graph_or_fql);
			// startActivity(myIntent);
		}

		public void onFacebookError(FacebookError error) {
			dialog.dismiss();
			Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * callback for the photo upload
	 */
	public class PhotoUploadListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			dialog.dismiss();

			Toast toast = Toast.makeText(getApplicationContext(), "Upload Photo executed", Toast.LENGTH_SHORT);
			toast.show();
			// mHandler.post(new Runnable() {
			//
			// public void run() {
			// new UploadPhotoResultDialog(HaiVLActivity.this,
			// "Upload Photo executed", response).show();
			// }
			// });
		}

		public void onFacebookError(FacebookError error) {
			dialog.dismiss();
			Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	public class FQLRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			mHandler.post(new Runnable() {

				public void run() {
					Toast.makeText(getApplicationContext(), "Response: " + response, Toast.LENGTH_LONG).show();
				}
			});
		}

		public void onFacebookError(FacebookError error) {
			Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	/*
	 * Callback for fetching current user's name, picture, uid.
	 */
	public class UserRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

				final String picURL = jsonObject.getJSONObject("picture").getJSONObject("data").getString("url");
				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");
				AppSettingParams.userDisplayName = name;
				AppSettingParams.userAvatar = picURL;
				
				AppSettingParams.save(MoreActivity.this);

				mHandler.post(new Runnable() {

					public void run() {
						setInfoAndVisibleLayout(picURL, name);
					}
				});

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	/*
	 * The Callback for notifying the application when authorization succeeds or
	 * fails.
	 */

	public class FbAPIsAuthListener implements AuthListener {

		public void onAuthSucceed() {
			requestUserData();
		}

		public void onAuthFail(String error) {
			System.out.println("onAuthFail = ");
		}
	}

	/*
	 * The Callback for notifying the application when log out starts and
	 * finishes.
	 */
	public class FbAPIsLogoutListener implements LogoutListener {

		public void onLogoutBegin() {
			Toast.makeText(getApplicationContext(), "�?ăng xuất tài khoản...", Toast.LENGTH_SHORT).show();
		}

		public void onLogoutFinish() {
			Toast.makeText(getApplicationContext(), "�?ăng xuất thành công...", Toast.LENGTH_LONG).show();
			mLoginButton.setVisibility(View.VISIBLE);
			userInfoLayout.setVisibility(View.GONE);
			AppSettingParams.userDisplayName = "";
			AppSettingParams.userAvatar = "";
			userDisplayName.setText("");						
			Utility.mFacebook.setAccessToken(null);
			SessionStore.clear(MoreActivity.this);
		}
	}

	public void requestUserData() {
		mLoginButton.setVisibility(View.GONE);

		if (AppSettingParams.userDisplayName.equals("")) {
			Toast.makeText(getApplicationContext(), "�?ang lấy thông tin của bạn...", Toast.LENGTH_LONG).show();

			SessionStore.save(Utility.mFacebook, MoreActivity.this);

			// mText.setText("Fetching user name, profile pic...");
			Bundle params = new Bundle();
			params.putString("fields", "name, picture");
			Utility.mAsyncRunner.request("me", params, new UserRequestListener());
		} else {
			mHandler.post(new Runnable() {

				public void run() {
					setInfoAndVisibleLayout(AppSettingParams.userAvatar, AppSettingParams.userDisplayName);
				}
			});
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void getMenuMore() {
		modules = new ArrayList<MenuMoreItem>();

//		modules.add(new MenuMoreItem("Xem truyện đã lưu", MenuMoreItem.VIEW_OFFLINE, R.drawable.ic_saved_comic));
//		modules.add(new MenuMoreItem("Cư�?i tiếp với epic", MenuMoreItem.MORE_EPIC, R.drawable.epic));
//		modules.add(new MenuMoreItem("Tiện ích b�? túi", MenuMoreItem.UTILS_WEB, R.drawable.ic_utils));
//		modules.add(new MenuMoreItem("�?ổi chủ đ�? mặc định", MenuMoreItem.SETTING_APP, R.drawable.ic_setting));
		modules.add(new MenuMoreItem("Liên hệ tác giả", MenuMoreItem.CONTACT_PR, R.drawable.ic_about));
		
//		modules.add(new MenuMoreItem("Clear", 11111, R.drawable.ic_about));
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {

		if (modules != null && index > -1 && index < modules.size()) {
			MenuMoreItem selected = modules.get(index);
			if (selected != null) {
				final int id = selected.getId();

				Intent intent = null;
				switch (id) {
				case 11111 :					
					SessionStore.clear(this);
					break;
				case MenuMoreItem.UTILS_WEB :
					intent = new Intent(getApplication(), UtilsWebActivity.class);
					startActivity(intent);
					break;
				case MenuMoreItem.VIEW_OFFLINE:
					intent = new Intent(getApplication(), LocalViewTopicActivity.class);
					startActivity(intent);
					break;
				case MenuMoreItem.MORE_EPIC:
					intent = new Intent(getApplication(), EpicVnActivity.class);
					startActivity(intent);
					break;
				case MenuMoreItem.SETTING_APP:
					changeDefaultTopic();
					break;
				case MenuMoreItem.CONTACT_PR:
					intent = new Intent(getApplication(), ContactMeActivity.class);
					startActivity(intent);
					break;
				}
			}
		}
	}

	AlertDialog topicListDialogChoicer = null;

	void doChange(final ArrayList<TopicHaiBlData> topicLists) {
		if (topicLists != null && !topicLists.isEmpty()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Ch�?n chủ đ�?");

			final String[] choiceList = new String[topicLists.size()];
			final int size = topicLists.size();
			for (int index = 0; index < size; index++) {
				choiceList[index] = topicLists.get(index).getName();
			}
			int selected = -1;
			builder.setSingleChoiceItems(choiceList, selected, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					final TopicHaiBlData haiBlData = topicLists.get(which);

					TopicHaiBlData dataDefault = new TopicHaiBlData(haiBlData.getId(), haiBlData.getName());
					ComicBussiness.getInstance(MoreActivity.this).setDefaultComicTopic(dataDefault);

					ComicSessionStore.saveDefaultTopic(dataDefault, MoreActivity.this);

					Toast.makeText(MoreActivity.this, "�?ã dùng " + dataDefault.getName() + " làm chủ đ�? mặc định", 1000).show();

					topicListDialogChoicer.dismiss();
				}
			});
			builder.setNegativeButton("�?óng", null);
			topicListDialogChoicer = builder.create();
			topicListDialogChoicer.show();
		}
	}

	private void doContact() {

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Liên hệ");
		alert.setMessage("Nếu bạn có nhu cầu quảng cáo, quảng bá sản phẩm của mình tới ngư�?i sử dụng, vui lòng liên hệ tới mình nhé! ^^");
		alert.setPositiveButton("Liên hệ", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				Intent i = new Intent(Intent.ACTION_SEND);
				i.setType("message/rfc822");
				i.putExtra(Intent.EXTRA_EMAIL, new String[] { "thanhle.hoangthanh0@gmail.com" });
				i.putExtra(Intent.EXTRA_SUBJECT, "V/v HaBL Application");
				i.putExtra(Intent.EXTRA_TEXT, "");
				try {
					startActivity(Intent.createChooser(i, "Send mail..."));
				} catch (android.content.ActivityNotFoundException ex) {
					DisplayUtils.openNoticeDialog("Lỗi", "Vui lòng liên hệ \nSố điện thoại: 0916.916.295 \nEmail: thanhle.hoangthanh0@gmail.com", MoreActivity.this, null);
					Toast.makeText(MoreActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
				}

			}
		});
		alert.setNeutralButton("Thông tin", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				DisplayUtils.openNoticeDialog("Thông tin", "Vui lòng liên hệ \nSố điện thoại: 0916.916.295 \nEmail: thanhle.hoangthanh0@gmail.com", MoreActivity.this, null);
			}
		});
		alert.setNegativeButton("�?óng", null);
		alert.show();

	}

	private void changeDefaultTopic() {
		final ArrayList<TopicHaiBlData> topicLists = (ArrayList<TopicHaiBlData>) ComicBussiness.getInstance(this).getComicTopicList().clone();
		if (topicLists == null || (topicLists != null && topicLists.isEmpty())) {
			DisplayUtils.openNoticeDialog("Thông báo", "Bạn vẫn chưa tạo chủ đ�? nào cả, hãy bắt đầu tạo 1 chủ đ�? từ các trang truyện nào.", this, null);
		} else {

			TopicHaiBlData defaultTopic = ComicBussiness.getInstance(this).getDefaultComicTopic();
			if (defaultTopic != null) {
				if (topicLists.size() == 1) {
					DisplayUtils.openNoticeDialog("Thông báo", "Bạn chỉ có 1 chủ đ�? duy nhất (" + defaultTopic.getName() + " đang là chủ đ�? mặc đinh)", this, null);
				} else {

					final int size = topicLists.size();
					for (int i = 0; i < size; i++) {
						TopicHaiBlData tmp = topicLists.get(i);
						if (tmp.getId() == defaultTopic.getId()) {
							topicLists.remove(i);
							break;
						}
					}

					DisplayUtils.openConfirmDialog("Xác nhận thay đổi", "Bạn đang dùng chủ đ�? " + defaultTopic.getName() + " làm mặc định, bạn muốn thay đổi?", this, new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							doChange(topicLists);
						}
					}, null);
				}
			} else {
				doChange(topicLists);
			}
		}
	}

}
